package sm.upgrade;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.dam.api.DBDictService;
import sm.dbdict.DBDictUtil;
import sm.dbdict.def.DBDict;
import sm.dbdict.def.Field;
import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;

public class Cm3rUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public void upgrade() {
		Object dbdict = template.get(DBDictService.DBDICT, "cm3r");
		if (dbdict != null) {
			SMMap dbdictMap = (SMMap) dbdict;
			DBDict des = (DBDict) dbdictMap.get(DBDictService.DESCRIPTOR);
			Field field = DBDictUtil.getFieldByNameIndexLevel(
					"vj.number.string.1", 57, 2, des.getField());
			if (field != null) {
				field.setName("vj.number.deprecate");
				try {
					template.update(DBDictService.DBDICT, dbdictMap);
					logger.info("Field Change: Field vj.number.string.1 renamed to vj.number.deprecate in table cm3r.");
				} catch (DataAccessException e) {
					logger.info("Field Change: Failed to rename from field vj.number.string.1 to vj.number.deprecate in table cm3r.");
				}

			}
		}

	}
}
